//
//  CycComposevViewController.swift
//  微博cyc
//
//  Created by cyc on 16/3/10.
//  Copyright © 2016年 cyc. All rights reserved.
//

import UIKit
import SnapKit
//8-10-4 枚举
enum ToolBarTagTyper:Int {
    case picture = 0
    case trend = 1
    case mention = 2
    case emoticon = 3
    case add = 4
}
// 8-7发微博的
class CycComposevViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置背景颜色
        view.backgroundColor=UIColor.whiteColor()
        //调用方法
        prepareUI()
    }
    //8-9发微博添加tooBar
    private func prepareUI(){
        setupNavigationBar()
        
        setupTextView()
        setuptooBar()
    }
    //8-12-1
    //设置TextView
    private func setupTextView(){
        // 添加子控件
        view.addSubview(textView)
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        //添加自动 调整scrollviewinsetS
        //前提：scrollview或子类所在的view是在导航栏里面
        //前提：scrollview或子类所在的控制器的view或者是在scrollview或子类view第一个子类view
        //automaticallyAdjustsScrollViewInsets=false
        //automaticallyAdjustsScrollViewInsets=true
        
        
    }

    
    
    // 8-9-3
    //设置tooBar
    
    private func setuptooBar(){
        //添加子控件
        view.addSubview(tooBar)
        //添加约束
        tooBar.snp_makeConstraints { (make) -> Void in
             make.leading.trailing.bottom.equalTo(view)
             make.height.equalTo(44)
        }
        // 第一中方法每个item对应的图片名称
//        let itemSettings = ["compose_toolbar_picture",
//              "compose_trendbutton_background",
//              "compose_mentionbutton_background",
//              "compose_emoticonbutton_background",
//              "compose_add_background"]
        // 修改-10-5
        // 每个item对应的图片名称
//        let itemSettings = [["imageName": "compose_toolbar_picture","tag":0],
//            ["imageName": "compose_trendbutton_background","tag":1],
//            ["imageName": "compose_mentionbutton_background","tag":2],
//            ["imageName": "compose_emoticonbutton_background","tag":3],
//            ["imageName": "compose_add_background","tag":4]]
        //第三种方法8-11使用名称设置toolBar点击事件
        let itemSettings = [["imageName": "compose_toolbar_picture","action":"picture"],
            ["imageName": "compose_trendbutton_background","action":"trend"],
            ["imageName": "compose_mentionbutton_background","action":"mention"],
            ["imageName": "compose_emoticonbutton_background","action":"emoticon"],
            ["imageName": "compose_add_background","action":"add"]]
        //先创建uibuttonitem
        tooBar.items = [UIBarButtonItem]()
        //8-10-3
       // var index = 0
        //8-9-2
         // 遍历 itemSettings 创建 UIBarbuttonItem
        for dict in itemSettings {
            //第二方法
            //let imageName = dict ["imageName"] as! String
            //第三种方法
            let imageName = dict ["imageName"]!

            
            let item = UIBarButtonItem(imageName: imageName)
            tooBar.items?.append(item)
            //8-10tooBar 按钮点击事件
            //8-10-1
            //获取 UIBarButtonItem里面的按钮
            let button = item.customView as! UIButton
            // 8-11-3
            //添加事件名称
            let action = dict["action"]!
            // 8-10-2
            // 添加点击事件
            
            // button.addTarget(self, action: "toolBarButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //8-11-添加点击事件
            //注意点可以直接放入String 如果是变量需要使用Selector
            button.addTarget(self, action:Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            //let tag = dict["tag"]as! Int
             //button.tag = tag
            //nrecognized selector sent to instance 0x7fc4b1c2c700' 没有加上@objc
              //index++
            //8-9-5添加弹簧
            tooBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //删除最后一个弹簧
        tooBar.items?.removeLast()
        //8-9完成
    }
    
    // 方法的导航栏
    /**
    设置导航栏的
    */
    private func setupNavigationBar(){
        // 控制导航栏的左右按钮和view
        setupBarButonItem()
        setupTitleView()
       
    }
        /**
     设置导航栏左右按钮
     */
    private func setupBarButonItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "colse")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        // 让barButton 不可用
        //当我点击取消的时候就出错了unrecognized selector sent to instance 0x7ff0fb498b10'
//解决的方法就是这个@objc
          navigationItem.rightBarButtonItem?.enabled = false
        
        
    }
    /**
     设置导航栏 tiltle
     */
    private func setupTitleView(){
        let prefix = "发微博"
        //测试
       // CZUserAccountViewModel.sharedInstance.userAccount?.screen_name=nil
        if let name = CZUserAccountViewModel.sharedInstance.userAccount?.screen_name{
            //有名称拼接名称
            //"\n"换行
            let title = prefix + "\n" + name
            //创建label
            let titlelabel=UILabel ()
            titlelabel.font=UIFont.systemFontOfSize(14)
            titlelabel.numberOfLines = 0
            titlelabel.textAlignment =  NSTextAlignment.Center
            // 8-8titlelabel.text=title
           //设置属性文本
             let attText = NSMutableAttributedString(string: title)
            // 添加属性
            //在整个字符串中查找name的range
            let range = (title as NSString).rangeOfString(name)
            //添加属性
            attText.addAttributes([NSForegroundColorAttributeName :UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
            // 8-8注意的地方是一定要设置属性attributedText再设置适配大小要不然四没有结果出现
            titlelabel.attributedText = attText
            //适配大小
            titlelabel.sizeToFit()
            navigationItem.titleView=titlelabel
        }else{
            //没有名称
            navigationItem.title=prefix
        }
        
    }
    // MARK: 1-按钮点击事件
    /**
    图片
    
    - parameter button: 按钮点击事件
    
    */
   @objc   private func picture(){
        print("点击图片")
    }
    /**
     
     
     - parameter button: <#button description#>
     */
   @objc  private func trend(){
        print("点击#")

    }
   @objc  private func mention(){
        print("点击@")

    }
  @objc   private func emoticon(){
        print("点击表情")

    }
  @objc   private func add (){
        print("点击 +")
        

    }
    //toolBarButtonClick点击事件
    //8-10-2
    @objc private func toolBarButtonClick (button :UIButton) {
        
         print(" 按钮被点击了:\(button.tag)")
        //8-10-4
        guard let type = ToolBarTagTyper(rawValue: button.tag)else{
            print("没有对应按钮")

            return
        }
        //8-10-3
        switch type{
        case .picture :
            print("点击图片")
        case .trend :
            print("点击#")
        case .mention:
            print("点击@")
        case .emoticon:
            print("点击表情")
           case.add:
            print("点击 +")

        }
    }
    //取消
    //解决问题的方法就是加上@objc
    @objc private   func colse(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发送微博
    func send(){
        print(" 发送微博")
    }
    //8-9发微博添加tooBar
    //MARK: 2懒加载
    //tooBar
    private lazy var tooBar: UIToolbar = {
        //创tooBar
        
        let tooBar=UIToolbar()
        
        return tooBar
    }()
    /*
    ios :中输入控件
    1.UITextile
      a.有占位文本
      b.只有一行
      c.不能滚动
    2.UITextView
      a.没有占位文本
      b.可以显示多行
      c.可以滚动
    
    
    
    */
    // MARK: 3UITextView
   // 8-12自定义CycPlaceholderTextView

//    private lazy var textView:UITextView = {
//        let tv = UITextView()
//        tv.alwaysBounceVertical=true
//
//        tv.font = UIFont.systemFontOfSize(18)
//        tv.text="分享新鲜事。。。。。。。。"
//        // textview的键盘退出方法
//        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
//        // 添加占位文本
//        let placehoderlabel = UILabel()
//        tv.addSubview(placehoderlabel)
//        placehoderlabel.text="分享新鲜事。。。。。。。。"
//        placehoderlabel.font=tv.font!
//    
//        placehoderlabel.textColor=UIColor.lightGrayColor()
//        placehoderlabel.sizeToFit()
//        //使用系统约束
//        placehoderlabel.translatesAutoresizingMaskIntoConstraints=false
//        //tv.backgroundColor=UIColor.redColor()
//        tv.addConstraint(NSLayoutConstraint(item: placehoderlabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: tv, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
//         tv.addConstraint(NSLayoutConstraint(item: placehoderlabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: tv, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
//        return tv
//    }()
    //修改8-12-3
    private lazy var textView:CycPlaceholderTextView = {
        let tv = CycPlaceholderTextView()
        tv.alwaysBounceVertical=true
        
        tv.font = UIFont.systemFontOfSize(18)
       
        // textview的键盘退出方法
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
       // tv.placeholderlabel.text = "分享新鲜事。。。。。。。。"
        tv.placeholde = "分享新鲜事。。。。。。。。"
        // 设置代理监听textView文字的改变
        tv.delegate = self

        return tv
    }()

}
// MARK: - 扩展 CycComposevViewController 实现 UITextViewDelegate
extension CycComposevViewController: UITextViewDelegate {
    /// 监听文字的改变
    func textViewDidChange(textView: UITextView) {
        // 有文字rightBarButtonItem可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

//8-7设置微博导航栏完成
// 8-8使用属性文本设置发微博标题
//8-9发微博添加tooBar
//8-10tooBarbutton的点击事件
// 8-11使用名称设置toolBar点击事件
////nrecognized selector sent to instance 0x7fc4b1c2c700' 没有加上@objc
//8-12自定义CycPlaceholderTextView
//8-13CycPlaceholderTextView 简体内容改变在发微博里

